﻿using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class MyMesh : MonoBehaviour
{
    private MeshRenderer mRenderer;
    private MeshFilter mFilter;
    public Material mat;
    public int rows = 100;
    public int clos = 100;

    private Mesh mMesh;

    void Start ()
    {
        this.mRenderer = this.GetComponent<MeshRenderer>();
        this.mFilter = this.GetComponent<MeshFilter>();

        mMesh = new Mesh
        {
            hideFlags = HideFlags.DontSave
        };

        List<Vector3> inVertices = new List<Vector3>();
        List<Vector2> uvs = new List<Vector2>();
        List<int> indexBuffer = new List<int>();

        for (int i = 0; i < clos; i++)
        {
            for (int j = 0; j < rows; j++)
            {
                AddVertices(inVertices, i, j, uvs, 1f / rows, 1f / clos);
                int index = ((i * rows) + j) * 4;
                AddTriangle(indexBuffer, index);
            }
        }

        mMesh.Clear();
        mMesh.SetVertices(inVertices);
        mMesh.SetUVs(0, uvs);
        mMesh.triangles = indexBuffer.ToArray();
        mMesh.RecalculateNormals();
        mMesh.name = "MyMesh";

        mFilter.mesh = mMesh;
        mRenderer.material = mat;
    }

    //2 3
    //0 1
    private void AddVertices(List<Vector3> inVertices, int x, int y, List<Vector2> uvs, float uRate, float vRate)
    {
        inVertices.Add(new Vector3(x, 0, y));
        inVertices.Add(new Vector3(x + 1, 0, y));
        inVertices.Add(new Vector3(x, 0, y + 1));
        inVertices.Add(new Vector3(x + 1, 0, y + 1));

        uvs.Add(new Vector2(x * uRate, y * vRate));
        uvs.Add(new Vector2((x + 1) * uRate, y * vRate));
        uvs.Add(new Vector2(x * uRate, (y + 1) * vRate));
        uvs.Add(new Vector2((x + 1) * uRate, (y + 1) * vRate));
    }

    private void AddTriangle(List<int> indexBuffer, int index)
    {
        indexBuffer.Add(index + 1);
        indexBuffer.Add(index + 0);
        indexBuffer.Add(index + 2);
        indexBuffer.Add(index + 2);
        indexBuffer.Add(index + 3);
        indexBuffer.Add(index + 1);
    }

    void Update ()
    {
		
	}
}
